<template>
  <template v-if="$auth(auth)">
    <el-button icon="Download" v-bind="$attrs" @click="open"><slot>导入</slot></el-button>
    <el-dialog v-if="load" :close-on-click-modal="false" title="导入" v-model="visible" class="auto" align-center width="600px" @close="handleClose">
      <p class="font-bold">第 1 步：点击下载模版</p>
      <a :href="downloadUrl"
        class="bg-gray-50 flex items-center justify-center rounded-md p-3 mt-2 cursor-pointer border border-gray-50 hover:border-gray-300">
        <div class="text-blue-600 flex items-center gap-1">
          <el-icon>
            <Download />
          </el-icon>下载模板
        </div>
      </a>
      <p class="my-4 font-bold">第 2 步：按照模版要求填写</p>
      <p class="font-bold mb-2">第 3 步：上传填写完成的文件</p>
      <el-upload ref="upload" v-model:file-list="fileList" accept=".csv,.xml,.xlsx" class="v-import" drag :limit="1"
        :on-exceed="handleExceed" :auto-upload="false">
        <div class="text-blue-600 flex items-center gap-1">
          <el-icon>
            <Upload />
          </el-icon>上传文件
        </div>
      </el-upload>
      <template v-if="resultStatus">
        <p class="font-bold mb-2">第 4 步：下载结果: {{resultStatus.count}}</p>
        <a :href="resultStatus.error_file_url"
           class="bg-red-400 flex items-center justify-center rounded-md p-3 mt-2 cursor-pointer border border-gray-50 hover:border-gray-300">
          <div class="text-white flex items-center gap-1">
            <el-icon>
              <Download />
            </el-icon>下载失败原因
          </div>
        </a>
      </template>
      <template #footer>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loadings.submit" :disabled="!fileList.length" class="ml-3" @click="submit">导
          入</el-button>
      </template>
    </el-dialog>
  </template>
</template>

<script setup>
import api from './api'
import { ElMessage, ElMessageBox, genFileId, ElNotification } from 'element-plus'
import { $auth } from "@/utils"
const load = ref(false)
const visible = ref(false)

const props = defineProps({
  importUrl: { type: String, default: '' },
  downloadUrl: { type: String, default: '' },
  tableRef: { type: Object, default: () => ({}) },
  auth: { type: String, default: '' },
  task: Boolean,
})

let loadings = reactive({})

const resultStatus = ref()

const emit = defineEmits(['close', 'success'])

const fileList = ref([])
const upload = ref()
const handleExceed = (files) => {
  upload.value?.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value?.handleStart(file)
}

// 打开弹窗
const open = async (selection) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  resultStatus.value = null
  fileList.value = []
}
// 提交
const submit = () => {
  loadings.submit = true
  const params = new FormData()
  fileList.value.forEach(d => {
    params.append('file', d.raw)
  })
  api.submit(props.importUrl, params).then(res => {
    const {code, data, message} = res
    const skip = data?.skip || []
    if (data.result) {
      emit('success')
      resultStatus.value = null
      ElMessage.success('导入成功')
      close()
      return
    } else {
      resultStatus.value = data
    }
    if (skip.length) {
      ElMessageBox({
        title: '导入提示',
        confirmButtonText: '跳过导入',
        cancelButtonText: '取消导入',
        message: h('p', null, [
        message.split('第').filter(Boolean).map(d => h('p', null, `第${d}`)),
          h('p', null, '是否跳过导入?'),
        ]),
      }).then(() => {
        skip.forEach(d => {
          params.append('skip[]', d)
        })
        api.submit(props.importUrl, params).then(res => {
          emit('success', res.data)
          ElMessage({ type: 'success', message: '导入成功', })
          close()
        })
      })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    } else {
      ElNotification.error({ title: res.message })
    }
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>

<style lang="scss">
.v-import {
  .el-upload-dragger {
    padding: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>